package com.example.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.Post;
import com.example.mapper.PostMapper;
import com.example.service.PostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 公众号：java思维导图
 * @since 2019-09-05
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public void initIndexWeekRank() {

        //获取最近评论的文章
        List<Post> last7DayPosts = this.list(new QueryWrapper<Post>()
                .ge("created", DateUtil.offsetDay(new Date(), -7).toJdkDate())
                .select("id, title, user_id, comment_count, view_count, created "));

        for(Post post : last7DayPosts) {
            String key = "day_rank:" + DateUtil.format(post.getCreated(), DatePattern.PURE_DATE_FORMAT);

            long between = DateUtil.between(new Date(), post.getCreated(), DateUnit.DAY);
            // 有效期
            long expiretime = (7 - between) * 24 * 60 * 60;

            redisUtil.zSet(key, post.getId(), post.getCommentCount());
            redisUtil.expire(key, expiretime);

            this.hashCachePostIdAndTitle(post);
        }


        // 把对应的评论数量设置到zset中
        this.zunionAndStoreLast7DaysForLastWeekRank();

    }

    public void hashCachePostIdAndTitle(Post post) {

        String key = "post_" + post.getId();

        boolean isExist = redisUtil.hasKey(key);
        if(!isExist) {

            long between = DateUtil.between(new Date(), post.getCreated(), DateUnit.DAY);
            // 有效期
            long expiretime = (7 - between) * 24 * 60 * 60;

            redisUtil.hset(key, "post:id", post.getId(), expiretime);
            redisUtil.hset(key, "post:title", post.getTitle(), expiretime);
//            redisUtil.hset(key, "post:avatar", post.getTitle(), expiretime);
        }
    }

    @Override
    public void zunionAndStoreLast7DaysForLastWeekRank() {

        String prifix = "day_rank:";

        List<String> otherKeys = new ArrayList<>();
        String key = "day_rank:" + DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT);


        for(int i = -6; i < 0; i++) {
            Date date = DateUtil.offsetDay(new Date(), i).toJdkDate();
            otherKeys.add(prifix + DateUtil.format(date, DatePattern.PURE_DATE_FORMAT)); // day_rank:yyyyMMdd
        }

        redisUtil.zUnionAndStore(key, otherKeys, "week_rank");
    }
}
